/* 
 * av Morten Calsson
 * Not yet implemented
 */

$(document).ready(function() {
	var geocoder = new google.maps.Geocoder();
	var total;
	var progress = 0;
	var failList;
	var list;
	var BARS;
	var RESULT; 
	var missing_list = [];
	
	prepareGetBarsWithoutGeolocation();
	bind();
	
	function bind(){
		$("#getGeoLocBtn").unbind("click").bind("click",function(){
			$("#getGeoLocBtn").hide();
			list = [];
			failList = [];
			$("#missingTable").show();
			$.when(getBars()).then(function(result){	
				BARS = result;
				for(var i = 0;i < result.length;i++){
					list.push(result[i].adress + "," + result[i].postnummer + " " + result[i].poststedNavn);
				}
				setUpGetGeoLocation();
			})
			
		});
		$("#reFetchGeoLocBtn").unbind("click").bind("click",function(){
			setUpGetGeoLocation();
		});
	}
	function prepareGetBarsWithoutGeolocation(){
		list = [];
		failList = [];
		$.when(getBarsWithoutGeolocation()).then(function(result){	
			var ret = "";
			BARS = result;
			var numberOfBarsWithoutGeoLoc = result.length;
			if(result.length > 0){
				$("#missingTable").slideDown("slow");
			}
			for(var i = 0; i < numberOfBarsWithoutGeoLoc; i++){
				ret += "<tr><td>" + result[i].id + "</td><td>" + result[i].name + "</td><td>" + result[i].adress + "</td></tr>";
			}
			for(var i = 0;i < result.length;i++){
				list.push(result[i].adress + "," + result[i].postnummer + " " + result[i].poststedNavn);
			}			
			$("#missingTable").append(ret);
		});
	}
	function setUpGetGeoLocation(){
		total = list.length;
		var getLocation = function (adress){
			$.when(getGeoLocation(adress)).then(function(result){
				var percent = ((progress / total) * 100)
				var ret = "Hentet <b>" + progress + "</b> av <b>" + total + "</b> (" + percent + " %)."
				$("#updateInfo").html(ret);
				$("#resultTable").append("<tr><td>" + progress + "</td><td>" + BARS[progress - 1].name + "</td><td>" + list[progress - 1] + "</td><td>" + result + "</td></tr>");

				$.when(saveGeoLocationToDB({ gymID : BARS[progress - 1].id, latlong : result})).then(function(){
					if(progress <= total){
						setTimeout(function(){
							getLocation(list[progress])
						},1000);
					}else{
						if(failList.length > 0){
							var ret = "<span style='color:black;font-size:16px;'>Kunne ikke hente geo lokasjon for disse senterene:</span> <br/>";
							for(var i = 0; i < failList.length;i++){
								ret += "- " + failList[i] + ".<br/>";
							}
							$("#failList").html(ret);
						}
					}				
				});
			}).fail(function(result){
				failList.push(result);
				var ret = "Kunne ikke hente geo lokasjon for disse senterene: <br/>";
				ret += "- " + result + ".<br/>";
				$("#failList").append(ret);
				if(progress < total){
					setTimeout(function(){
						getLocation(list[progress])
					},1000);
				}
			});
		}
		$("#missingTable").hide();
		$("#resultTable").show();
		$("#reFetchGeoLocBtn").hide();
		$("#getGeoLocBtn").hide();
		$("#headerMissing").hide();
		getLocation(list[0]);
	}
	function getGeoLocation(addressData){
		var dfd = new $.Deferred();
		geocoder.geocode({
			'address': addressData
		}, function (results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				var result = results[0].geometry.location;
				progress++
				dfd.resolve(result);
			} else {
				progress++
				dfd.reject(addressData);
			}
		});		
		return dfd.promise();
	}
	
	function getBars() {
		var dfd = new $.Deferred();
			$.ajax({
                    type: "GET",
                    url: "./helpers/getBarsForGeoLocationUpdate.php",
					data: {
						action: 'getBarsForGeoLocationUpdate'
					},
                    cache: false,
                    success: function(data)
                        {
							data = JSON.parse(data);
							dfd.resolve(data);
                        }
			});
			return dfd.promise();	
	}
	
	
	function getBarsWithoutGeolocation() {
		var dfd = new $.Deferred();
			$.ajax({
                    type: "GET",
                    url: "./helpers/getBarsWithoutGeolocation.php",
					data: {
						action: 'getBarsWithoutGeolocation'
					},
                    cache: false,
                    success: function(data)
                        {
							data = JSON.parse(data);
							dfd.resolve(data);
                        }
			});
			return dfd.promise();	
	}
	
	function saveGeoLocationToDB(args) {
		var dfd = new $.Deferred();
		$.ajax({
				type: "POST",
				url: "./helpers/updateGeoLocation.php",
				data: {
					action: 'updateGeoLocation',
					gymID : args.gymID,
					geoLocation : args.latlong.toString()
				},
				cache: false,
				success: function(data)
					{
						dfd.resolve();
					}
		});
		return dfd.promise();	
	}
		
	
	
});